﻿using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Treely.Data.Model;
using Treely.Data.Model.Abstract;

namespace Treely.Data
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public string UserId { get; set; }

        public ApplicationDbContext(string userId)
            : base("DefaultConnection")
        {
            UserId = userId;
            Database.SetInitializer<ApplicationDbContext>(null);
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext("System");
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }

        public DbSet<MathQuizTemplate> MathQuizTemplates { get; set; }

        public DbSet<MathQuizTemplateSection> MathQuizTemplateSections { get; set; }

        public override int SaveChanges()
        {
            var objectStateManager = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager;
            var addedEntities = objectStateManager.GetObjectStateEntries(EntityState.Added)
                .Where(x => x.Entity is AuditObject)
                .ToList();
            addedEntities.ForEach(x =>
            {
                var addedAuditObject = x.Entity as AuditObject;
                if (addedAuditObject != null)
                {
                    addedAuditObject.Created = DateTime.Now;
                    addedAuditObject.CreatedById = UserId;
                }
            });
            var modified = objectStateManager.GetObjectStateEntries(EntityState.Modified).ToList();
            modified.ForEach(x =>
            {
                var modifiedAuditObject = x.Entity as AuditObject;
                if (modifiedAuditObject != null)
                {
                    modifiedAuditObject.Modified = DateTime.Now;
                    modifiedAuditObject.ModifiedById = UserId;
                }
            });
            return base.SaveChanges();
        }
    }
}